<template xmlns="http://www.w3.org/1999/html">
  <FireWork/>
  <el-container>
    <el-header>
      <el-row class="top-bar">
        <el-col :span="6">
          <div class="grid-content"/>
          <a @click="goToNewsPage" style="color: black;cursor: pointer;">新闻</a>
        </el-col>
        <el-col :span="6">
          <div class="grid-content"/>
          <a @click="goToAddArticlePage" style="color: black;cursor: pointer;">发布文章</a>
        </el-col>
        <el-col :span="6">
          <div class="grid-content"/>
          <a @click="goToArticlePage(17)" style="color: black;cursor: pointer">开发日志</a>
        </el-col>
        <el-col :span="6">
          <div class="grid-content"/>
          <Avatar/>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-row>
        <el-col :span="6" style="display: flex;justify-content: center;text-align: center;margin-top: 100px">
          <div v-if="seckillBeanActivityInfo">
            <h2>活动场次: {{ seckillBeanActivityInfo.sessionName }}</h2>
            <h3>仙豆总份数: {{ seckillBeanActivityInfo.seckillCount }} · 单份仙豆数:
              {{ seckillBeanActivityInfo.beanCount }}</h3>
            <h3>每人限抢: {{ seckillBeanActivityInfo.seckillLimit }} 份</h3>
            <el-button @click="seckillBean">抢仙豆</el-button>
          </div>
        </el-col>
        <el-col :span="12" style="margin-top: 50px">
          <div v-for="article in articleList" :key="article.id">
            <el-row class="article-item">
              <el-col :span="4"></el-col>
              <el-col :span="16">
                <div @click="goToArticlePage(article.id)" class="article-container">
                  <div class="article-content">
                    <h2 class="article-title">{{ article.title }}</h2>
                    <div class="article-content-truncated">
                      {{ article.content.length > 50 ? article.content.substring(0, 50) + '...' : article.content }}
                    </div>
                    <div class="article-meta-container">
                      <div>{{ article.nickname }} · {{ article.updateTime.substring(0, 10) }} ·
                        阅读量:{{ article.viewCount }} ·
                        评论:{{ article.commentCount }} · 点赞数:{{ article.likeCount }}
                      </div>
                    </div>
                    <el-divider/>
                  </div>
                </div>
              </el-col>
              <el-col :span="4"></el-col>
            </el-row>
          </div>

        </el-col>

        <el-col :span="6">
          <!--签到板块-->
          <div>
            <div style="text-align: center;">
              <el-text>累计签到{{ signInCount }}天</el-text>
            </div>
            <el-calendar :range="dateRange" class="custom-calendar">
              <template #header>
                <span>{{ new Date().getFullYear() }}年 {{ new Date().getMonth() + 1 }}月</span>
                <el-text v-if="(signInCountStatus[(new Date().getDate()) - 1]) === 0">今天记得签到哦👀</el-text>
                <el-text v-if="(signInCountStatus[(new Date().getDate()) - 1]) === 1">今天已签到👍</el-text>
              </template>
              <template #date-cell="{ data }">
                <div :class="['cellStyle',getCellColorClass(data)]">
                  <p :class="data.isSelected ? 'is-selected' : ''"
                     @click="clickDate(data)">
                    {{ data.day.split('-')[2] }}
                    <br/>
                    <span v-if="(signInCountStatus[data.day.split('-')[2] - 1] !=null)&&(isMonth(data))"> {{
                        (signInCountStatus[data.day.split('-')[2] - 1] === 1) ? '✔' : '✖'
                      }}</span>

                    <br/>
                  </p>
                </div>
              </template>
            </el-calendar>
            <div style="margin-left: 40px;margin-top: 80px">
              <el-divider/>
              <a href="https://beian.miit.gov.cn/" target="_blank">沪ICP备2024067823号-1</a>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-main>
    <el-backtop :bottom="100">
      <div
          style="
        width: 100%;
        height: 100%;
        background-color: var(--el-bg-color-overlay);
        box-shadow: var(--el-box-shadow-lighter);
        text-align: center;
        line-height: 50px;
        color: black;
      "
      >
        <img src="@/assets/svg/top-20.svg"/>
      </div>
    </el-backtop>
  </el-container>

</template>

<script setup>
import {onMounted, ref, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import {GetSignInStatus, SignIn, SignInCount} from "@/api/member/user.js";
import {useUserinfo} from '@/components/hooks/useUserinfo'
import {ListArticleAll} from "@/api/member/article.js";
import {GetSeckillBeanActivity, SeckillBean} from "@/api/member/seckill.js";
import Avatar from '@/components/Avatar/Avatar.vue'


const router = useRouter()
const {userinfo} = useUserinfo()


/** 获取抢仙豆活动信息 **/
const seckillBeanActivityInfo = ref()
const getSeckillBeanActivity = async () => {
  const {code, data, msg} = await GetSeckillBeanActivity();
  if (code === 200) {
    seckillBeanActivityInfo.value = data;
  } else {
    ElMessage.error(msg)
  }
}


/** 抢仙豆 **/
const seckillBean = async () => {
  const params = {
    userId: userinfo.value.id,
    seckillCount: 1
  }
  const {code, msg} = await SeckillBean(params)
  if (code === 200) {
    ElMessage.success(msg)
  } else {
    ElMessage.error(msg)
  }
  setTimeout(() => {
    window.location.reload();
  }, 1500);
}

/** 日历 **/
/** 日历显示时间范围 **/
const dateRange = ref()
const calendarRange = () => {
  // 获取当前日期
  const now = new Date()
  // 获取本月的第一天
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
  // 获取本月的最后一天
  // 设置日期为下个月的第0天，即本月的最后一天
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  // 返回包含本月第一天和最后一天的数组
  dateRange.value = [firstDay, lastDay]
  // console.log(dateRange)
}


/** 签到 **/
const clickDate = async (data) => {
  const today = new Date();
  const targetDate = new Date(data.day);
  // 清除时间部分，只比较日期部分
  today.setHours(0, 0, 0, 0)
  targetDate.setHours(0, 0, 0, 0)
  if (today.getTime() === targetDate.getTime()) {
    // console.log('date:', data.day)
    // console.log('Day:', data.day.split('-')[2])

    const {code, msg} = await SignIn(userinfo.value.id)
    if (code === 200) {
      ElMessage.success(msg)
    } else {
      ElMessage.error(msg)
    }
    setTimeout(() => {
      window.location.reload();
    }, 3000);
  }
}


/** 获取累计签到天数 **/
const signInCount = ref(0)
const fetchSignInCount = async () => {
  const {code, data, msg} = await SignInCount(userinfo.value.id)
  if (code === 200) {
    signInCount.value = data
  } else {
    ElMessage.error(msg)
  }
}


/** 获取用户当月签到状态 **/
const signInCountStatus = ref([])
const fetchSignInCountStatus = async () => {
  const {code, data, msg} = await GetSignInStatus(userinfo.value.id)
  if (code === 200) {
    signInCountStatus.value = data
  } else {
    ElMessage.error(msg)
  }
}


/** 判断是否为今天 **/
const isToday = (data) => {
  let currentDate = new Date();
  // console.log(currentDate)
  let currentDay = currentDate.getDate().toString();
  let currentMonth = (currentDate.getMonth() + 1).toString();
  let currentYear = currentDate.getFullYear().toString();

  if (currentDay.length === 1) {
    currentDay = '0' + currentDay;
  }
  if (currentMonth.length === 1) {
    currentMonth = '0' + currentMonth;
  }
  return currentYear === data.day.split('-')[0] && currentMonth === data.day.split('-')[1] && currentDay === data.day.split('-')[2]
}


/** 判断是否为这个月 **/
const isMonth = (data) => {
  let currentMonth = (new Date().getMonth() + 1).toString();
  if (currentMonth.length === 1) {
    currentMonth = '0' + currentMonth;
  }
  return currentMonth === data.day.split('-')[1]
}


/**  变更日历中今日所在表格的样式 **/
const getCellColorClass = (data) => {
  if (isToday(data)) {
    const index = data.day.split('-')[2] - 1
    const status = signInCountStatus.value
    const flag = (status[index]) === 1
    return {
      'cell-color': true, // 确保始终有这个基础类
      'cell-color-green': flag, // 如果返回true，则添加这个类
      'cell-color-yellow': !flag, // 如果返回false,则添加这个类
    }
  }
}


/** 获取文章数据 **/
let articleList = ref([]);
const fetchArticleAll = async () => {
  try {
    const {code, data, msg} = await ListArticleAll();
    if (code === 200) {
      const sortedArticleList = computed(() => {
        // 使用数组的sort方法，并传入一个比较函数来进行倒序排序
        return data.sort((a, b) => {
          // 假设updateTime是一个可以转换为Date对象的字符串
          const dateA = new Date(a.updateTime);
          const dateB = new Date(b.updateTime);
          // 返回一个负数、零或正数来指定排序顺序
          return dateB - dateA; // 降序排序（最新的在前面）
        });
      });
      articleList.value=sortedArticleList.value;
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    ElMessage.error(error)
  }
}


// 跳转发布文章页面
const goToAddArticlePage = () => {
  router.push('/goToAddArticlePage')
}


// 跳转文章详细页面
const goToArticlePage = (id) => {
  const resolved = router.resolve({
    name: 'ArticlePage',
    params: {id}
  });
  window.open(resolved.href, '_blank');
}


// 跳转新闻页面
const goToNewsPage = () => {
  router.push('/goToNewsPage')
}


onMounted(() => {
  calendarRange();
  fetchSignInCount();
  fetchSignInCountStatus();
  fetchArticleAll();
  getSeckillBeanActivity();
})
</script>


<style scoped>

.custom-calendar {
  /* 假设你有一个初始的 transform-origin，但通常默认为元素的中心 */
  transform-origin: center top; /* 你可以根据需要设置变换的原点 */

  /* 使用 transform: scale() 来缩小元素。0.5 表示缩小到原始尺寸的一半 */
  transform: scale(0.8);
}

.custom-calendar :deep(.el-calendar-day) {
  padding: 0;
  height: auto;
}

.cellStyle {
  /* 设置为块级元素，并填充整个宽度（默认为块级元素） */
  display: block;
  /* 如果需要，设置高度为 100%，但通常表格单元格的高度由内容决定 */
  height: 100%;
  /* 设置宽度为 100%，但这通常已经是默认行为 */
  width: 100%;
  /* 移除任何可能的边距或内边距，以确保 div 填满整个空间 */
  margin: 0;
  padding: 0;
  text-align: center;

}

.cell-color {
  background-color: yellow;
}

.cell-color-yellow {
  background-color: yellow;
}

.cell-color-green {
  background-color: greenyellow;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.top-bar {
  text-align: center;
}

</style>
